﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autofac;
using WinformDevFramework.Core.Configuration;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Services.System;
using HZH_Controls.Controls;
using System.Media;

namespace WinformDevFramework
{
    public partial class BaseForm1 : Form
    {
        // 分页相关变量
        protected int _currentPage = 1;
        protected int _pageSize = 20;
        protected int _totalCount = 0;


        protected FormStatus formStatus = FormStatus.First;

        /// <summary>
        /// 始终为readonly
        /// </summary>
        public List<string> ReadOnlyControlList = new List<string>();

        /// <summary>
        /// 始终为可编辑
        /// </summary>
        public List<string> EditControlList = new List<string>();

        public BaseForm1()
        {
            InitializeComponent();
        }

        public virtual void Init()
        {
            tabControl1.Selecting += TabControl1_Selecting;
            //设置list不可以编辑
            this.dataGridViewList.ReadOnly = true;
            //设置列宽自适应
            dataGridViewList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridViewList.AutoResizeColumns();
            //dataGridViewList.DoubleBuffered();
            //设置gridlist 双击事件
            this.dataGridViewList.CellDoubleClick += DataGridViewList_CellDoubleClick;

        }
        private void TabControl1_Selecting(object? sender, TabControlCancelEventArgs e)
        {
            TabControlSelectingFunction(sender, e);
        }

        /// <summary>
        /// tab页签禁止切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            if (formStatus == FormStatus.Edit || formStatus == FormStatus.Add)
            {
                e.Cancel = true;
            }
        }
        private void DataGridViewList_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                DataGridViewListDoubleClick(sender, e);
            }
        }
        /// <summary>
        /// datagridview双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            //跳转到详情页
            this.tabControl1.SelectedIndex = 1;
            //设置功能按钮状态
            formStatus = FormStatus.View;
        }
        private void Button_Click(object? sender, EventArgs e)
        {

        }

        private void BaseForm1_Load(object sender, EventArgs e)
        {
            Init();
        }
        /// <summary>
        /// 设置控件状态
        /// </summary>
        /// <param name="groupBox"></param>
        protected void SetControlStatus(Control groupBox, bool canEdit)
        {
            foreach (Control control in groupBox.Controls)
            {
                if (EditControlList.Contains(control.Name))
                {
                    control.Enabled = true;
                }

                if (ReadOnlyControlList.Contains(control.Name))
                {
                    control.Enabled = false;
                }

                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    textBox.ReadOnly = !canEdit;
                }
                else if (control is UITreeView || control is TreeView || control is LinkLabel || control is PictureBox)
                {

                }
                else if (control is DataGridView)
                {
                    //dataGridView可编辑
                    //DataGridView dataGridView = (DataGridView)control;
                    //dataGridView.Enabled = true;
                }
                else if (control.Controls.Count == 0)
                {
                    control.Enabled = canEdit;
                }

                SetControlStatus(control, canEdit);

            }
        }

        /// <summary>
        /// 清除控件值
        /// </summary>
        /// <param name="groupBox"></param>
        protected void ClearControlsText(Control groupBox)
        {
            foreach (Control control in groupBox.Controls)
            {
                if (control is DateTimePicker)
                {
                    control.Text = string.Empty;
                }
                else if (control is Label || control is Button || control is CheckBox || control is GroupBox || control is TabPage)


                {

                }
                ////else if (control is TextBox && (control.Name.Equals("")|| control.Name.Equals("")))
                ////{

                ////}
                else
                {
                    control.Text = string.Empty;
                }

                ClearControlsText(control);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddFunction(sender, e);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void AddFunction(object sender, EventArgs e)
        {
            //跳转到详情页
            this.tabControl1.SelectedIndex = 1;
            //设置功能按钮状态
            formStatus = FormStatus.Add;
        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            EditFunction(sender, e);
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void EditFunction(object sender, EventArgs e)
        {
            formStatus = FormStatus.Edit;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                SaveFunction(sender, e);
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void SaveFunction(object sender, EventArgs e)
        {
            formStatus = FormStatus.Save;
        }

        private void btnCanel_Click(object sender, EventArgs e)
        {
            CanelFunction(sender, e);
        }
        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void CanelFunction(object sender, EventArgs e)
        {
            formStatus = FormStatus.Canel;
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            DelFunction(sender, e);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void DelFunction(object sender, EventArgs e)
        {
            formStatus = FormStatus.Del;
        }
        private void btnResetPW_Click(object sender, EventArgs e)
        {
            ResetPWFunction(sender, e);
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void ResetPWFunction(object sender, EventArgs e)
        {

        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            CloseFunction(sender, e);
        }
        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public virtual void CloseFunction(object sender, EventArgs e)
        {
            TabControl parentTabControl = this.Parent.Parent as TabControl;
            TabPage tabpage = this.Parent as TabPage;
            parentTabControl.TabPages.Remove(tabpage);
        }
        /// <summary>
        /// 设置工具栏按钮是否隐藏
        /// </summary>
        protected void SetToolsButton()
        {
            //设置工具按钮
            var buttons = AppInfo.UserMenus.Where(p =>
                p.ParentID == int.Parse(this.Tag.ToString()) && p.MenuType == "Button").Select(p => p.MenuCode);
            foreach (Control control in this.flowLayoutPanelTools.Controls)
            {
                if (!buttons.Contains(control.Name))
                {
                    control.Hide();
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                formStatus = FormStatus.First;
                SetToolButtonStatus(formStatus);
            }
            else
            {
                if (!string.IsNullOrEmpty(txtID.Text))
                {
                    formStatus = FormStatus.View;
                    SetToolButtonStatus(formStatus);
                }
            }
        }

        /// <summary>
        /// 设置工具按钮是否可用
        /// </summary>
        public virtual void SetToolButtonStatus(FormStatus status)
        {
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        btnImport.Enabled = false;  // 新增导入按钮
                        btnExport.Enabled = false;  // 新增导出按钮
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        btnImport.Enabled = false;  // 编辑时禁用导入
                        btnExport.Enabled = false;   // 编辑时禁用导出
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        btnImport.Enabled = true;  // 浏览状态允许导入
                        btnExport.Enabled = true;  // 浏览状态允许导出
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        btnImport.Enabled = true;  // 取消后恢复导入
                        btnExport.Enabled = true;  // 取消后恢复导出
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        btnImport.Enabled = true;  // 初始状态允许导入
                        btnExport.Enabled = true;  // 初始状态允许导出
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        btnImport.Enabled = true;  // 保存后允许导入
                        btnExport.Enabled = true;  // 保存后允许导出
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        btnImport.Enabled = true;  // 删除后允许导入
                        btnExport.Enabled = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }

        }

        /// <summary>
        /// 校验数据
        /// </summary>
        /// <returns></returns>
        public virtual bool ValidateData()
        {
            return false;
        }



        public virtual void ImportFunction(object sender, EventArgs e)
        {

        }
        public virtual void ExportFunction(object sender, EventArgs e)
        {

        }
        public virtual void SearchFunction(object sender, EventArgs e)
        {
            _currentPage = 1;
            LoadData();
        }
        public virtual void FirstPageFunction(object sender, EventArgs e)
        {

            _currentPage = 1;
            LoadData();

        }
        public virtual void PrevPageFunction(object sender, EventArgs e)
        {
            if (int.TryParse(txtPage.Text, out int page) && page > 1)
            {
                _currentPage = page - 1;
                LoadData();
            }
        }
        public virtual void NextPageFunction(object sender, EventArgs e)
        {
            if (int.TryParse(txtPage.Text, out int page) && page < (_totalCount / _pageSize) + 1)
            {
                _currentPage = page + 1;
                LoadData();
            }
        }



        public virtual void LastPageFunction(object sender, EventArgs e)
        {

            _currentPage = (_totalCount + _pageSize - 1) / _pageSize;
            LoadData();

        }


        private void btnImport_Click(object sender, EventArgs e)
        {
            ImportFunction(sender, e);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportFunction(sender, e);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchFunction(sender, e);
        }
        private void btnFirstPage_Click(object sender, EventArgs e)
        {
            FirstPageFunction(sender, e);
        }

        private void btnLastPage_Click(object sender, EventArgs e)
        {
            LastPageFunction(sender, e);
        }
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            PrevPageFunction(sender, e);
        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            NextPageFunction(sender, e);
        }

        private void txtPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
            {
                e.Handled = true;
                SystemSounds.Beep.Play();
            }
        }
        private void txtPage_TextChanged(object sender, EventArgs e)
        {
            // 如果输入为空，不处理
            if (string.IsNullOrWhiteSpace(txtPage.Text))
                return;

            // 尝试解析页码
            if (int.TryParse(txtPage.Text, out int page) && page > 0)
            {
                _currentPage = page;
                LoadData(); // 自动加载数据
            }
        }




        protected virtual void LoadData()
        {
            // 基类中不实现具体逻辑，由子类实现
            txtPage.Text = _currentPage.ToString();
        }




        //更新分页UI状态
        protected void UpdatePaginationControls(int totalCount)
        {
            _totalCount = totalCount;
            _pageSize = Math.Max(1, _pageSize); // 确保最小分页大小

            int totalPages = (_totalCount + _pageSize - 1) / _pageSize;
            _currentPage = Math.Max(1, Math.Min(_currentPage, totalPages));

            // 更新UI
            txtPage.Text = _currentPage.ToString();
            lblPages.Text = $"第{_currentPage}页/共{totalPages}页";
            lblTotalCount.Text = $"总记录{totalCount}";
            // 按钮状态
            btnFirstPage.Enabled = _currentPage > 1;
            btnPrevPage.Enabled = _currentPage > 1;
            btnNextPage.Enabled = _currentPage < totalPages;
            btnLastPage.Enabled = _currentPage < totalPages;
        }

    
    }
}
